<?php
// +----------------------------------------------------------------------
// | @filename AdminUserLogic.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-28 12:20:06
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------

namespace Addons\Backend\Logics;


use Addons\Backend\Handlers\ImageUploadHandler;
use Addons\Backend\Helpers\ArrayHelper;
use Addons\Backend\Repositories\AdminUserRepository;
use Addons\Backend\Repositories\MenuRepository;
use Addons\Backend\Repositories\RoleRepository;
use Addons\Backend\Transformers\MenuTransformer;
use Addons\Backend\Transformers\RoleTransformer;
use Illuminate\Support\Facades\Auth;
use Addons\Backend\Transformers\AdminUserTransformer;

class AdminUserLogic extends BaseLogic
{
    protected $adminUserRepository;
    protected $adminUserTransformer;
    protected $roleRepository;
    protected $roleTransformer;
    protected $menuRepository;
    protected $menuTransformer;
    protected $imageUploadHandler;

    public function __construct(AdminUserRepository $adminUserRepository, AdminUserTransformer $adminUserTransformer,
                                RoleRepository $roleRepository, RoleTransformer $roleTransformer, MenuRepository $menuRepository,
                                MenuTransformer $menuTransformer,ImageUploadHandler $imageUploadHandler)
    {
        $this->adminUserRepository = $adminUserRepository;
        $this->adminUserTransformer = $adminUserTransformer;
        $this->roleRepository = $roleRepository;
        $this->roleTransformer = $roleTransformer;
        $this->menuRepository = $menuRepository;
        $this->menuTransformer = $menuTransformer;
        $this->imageUploadHandler = $imageUploadHandler;
    }

    /**
     * 获取管理员列表
     * @param $filters
     * @return array
     */
    public function list($filters): array
    {
        $adminUsers = $this->adminUserRepository->queryList($filters);
        return $this->success(fractal($adminUsers, $this->adminUserTransformer)->toArray());
    }

    /**
     * 获取管理员信息
     */
    public function info(): array
    {
        $adminUser = Auth::guard('backend')->user();
        return $this->success(fractal($adminUser, $this->adminUserTransformer)->toArray());
    }


    /**
     * 头像上传
     * @param $avatar
     * @return string
     */
    public function uploadAvatar($avatar): string
    {
        if (substr($avatar, 0, 5) == 'data:') {
            $uploadAvatarResult = $this->imageUploadHandler->save($avatar, 'admin-avatar', true, true);
            return $uploadAvatarResult['data']['path'];
        }else{
            return '';
        }
    }

    /**
     * 创建管理员
     * @param $data
     * @return array
     */
    public function create($data): array
    {
        $data['avatar'] = $this->uploadAvatar($data['avatar']);
        if (!$data['avatar']) {
            return $this->failed('创建管理员失败:头像上传失败');
        }
        $adminUser = $this->adminUserRepository->create($data);
        return $this->success(fractal($adminUser, $this->adminUserTransformer)->toArray(), '创建管理员操作成功');
    }

    /**
     * 更新管理员
     * @param $data
     * @return array
     */
    public function update($data): array
    {
        $data['avatar'] = $this->uploadAvatar($data['avatar']);
        if (!$data['avatar']) {
            return $this->failed('更新管理员失败:头像上传失败');
        }
        $adminUser = $this->adminUserRepository->update($data);
        return $this->success(fractal($adminUser, $this->adminUserTransformer)->toArray(), '更新管理员操作成功');
    }

    /**
     * 删除管理员
     * @param $id
     * @return array
     */
    public function delete($id): array
    {
        $adminUser = $this->adminUserRepository->findById($id);

        if (empty($adminUser)) {
            return $this->failed('管理员不存在');
        }

        return $this->adminUserRepository->delete($id) ? $this->success([], '删除管理员操作成功') : $this->failed([], '删除管理员操作失败');
    }

    /**
     * 给管理员分配角色
     * @param $data
     * @return array
     */
    public function assignRoles($data): array
    {
        $this->adminUserRepository->assignRoles($data['id'], $data['roles']);
        return $this->success([], '分配角色操作成功');
    }

    /**
     * 根据管理员ID获取管理员已授权的菜单
     * @param $userId
     * @return array
     */
    public function getUserMenus($userId): array
    {
        $user = $this->adminUserRepository->getUserMenus($userId);
        $userMenus = [];

        foreach ($user['roles'] as $role) {
            $userMenus = $role['menus'];
        }

        $userMenus = array_unique(fractal($userMenus, $this->menuTransformer)->toArray()['list'], SORT_REGULAR);

        return $this->success(['list' => ArrayHelper::makeTree($userMenus)], '获取菜单路由成功');
    }

    /**
     * 根据管理员ID获取管理员已授权的角色
     * @param $userId
     * @return array
     */
    public function getUserRoles($userId): array
    {
        $assignedRoles = fractal($this->adminUserRepository->assignedRoles($userId), $this->roleTransformer)->toArray()['list'];
        $allRoles = fractal($this->roleRepository->all(), $this->roleTransformer)->toArray()['list'];
        $assignedRoleIds = array_column($assignedRoles, 'id');

        return $this->success(['allRoles' => $allRoles, 'assignedRoles' => $assignedRoleIds]);
    }
}
